// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public'),
		clientApi = require('../../public/clientapi');

	var IndexBase  = require('../allindex/indexbase');

	var hsgtModel = require('./model');

	function HsgtzjModule () {
		this.domId = 'hsgtzj';
		this.MODULENAME = '境外资金';
		this.EXPLAINTEXT = '统计沪股通资金的流向。沪股通资金流向表明外资对于A股的青睐程度。若沪股通资金大幅流入，表明外资发现A股价值，积极进场吸纳筹码；反之则表示外资出逃，需保持谨慎。';

		this.type = 'min';

		// this.code = '883900,1A0001';
		// this.indexCode = '883900';
		this.hcType = 'hgtzjlxpjhc';

		this.latestVal1 = '--';
		this.latestVal2 = '--';

		this.beginDate = '';
		this.originalDateStr = '';

		this.HighchartsObj = null;
		this.renderDom();
	}

	publicMethod.extendClass(HsgtzjModule, IndexBase);

	HsgtzjModule.prototype.renderDom = function () {
		var self = this;
		var htmlDom = '<li data-mname="'+ self.domId +'">' +
					'<div class="module-item">' +
						'<div class="module-header">' +
							'<a href="###" class="icon module-close-btn"></a>' +
							'<div class="date-wrap">' +
								'<p class="date-wrap-single">' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'DatePicker" />' +
									'<a href="###" class="icon interval-btn" title="切换区间" id="'+ self.domId + 'IntervalBtn"></a>' +
								'</p>' +
								'<p class="date-wrap-interval hide">' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'SDatePicker" />' +
									'<i class="separator">-</i>' +
									'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'EDatePicker"  />' +
									'<a href="###" class="icon single-btn" title="切换区间" id="'+ self.domId + 'SingleBtn"></a>' +
								'</p>' +
							'</div>' +
							'<p class="module-name">'+ self.MODULENAME +'</p><i class="icon module-tip-btn" id="'+ self.domId +'ExplainBtn"><b class="icon"></b></i>' +
						'</div>' +
						'<div class="module-main">' +
							'<div class="chart-box" id="'+ self.domId +'ChartBox">' +
							'</div>' +
							'<div class="explain-box hide" id="'+ self.domId +'ExplainBox">' +
								'<p class="explain-text">'+ self.EXPLAINTEXT +'</p>' +
								'<div class="clearfix">' +
								'<div class="explain-left '+ self.domId +'-explain-pic">' +
								'</div>' +
								'<div class="explain-right">' +
									'<p class="explain-p">今日解读：<span id="'+ self.domId +'ExplainData">--</span></p>' +
									'<p>上涨概率回测</p>' +
									'<p id="'+ self.hcType +'HcData">历史数据回测中...</p>' +
								'</div>' +
								'</div>' +
							'</div>' +
							'<p class="non-trade-tip" id="'+ self.domId +'NonTradeTip">非交易日，请重新选择</p>' +
						'</div>' +
					'</div>' +
				'</li>';
				$('#modules-list-ul').append(htmlDom);
				self.renderData();

				self.bindEvents();
	}
	HsgtzjModule.prototype.renderData = async function() {
		var tradeDay = await clientApi.getTradingDay();

		this.requestMinData(tradeDay);

	}
	HsgtzjModule.prototype.requestMinData = function(date) {
		var self = this;
		self.beginDate = date;

		hsgtModel.getIsTrading(self.beginDate, function(result) {
			self.checkIsTrading(result);
		});

		this.getExplainData(date);
	}
	HsgtzjModule.prototype.checkIsTrading = function(result, isUpdate) {
		var self = this;
		var hgtFlow = '流入';
		var hgtContinuousDay = 0;
		if (result && result.errorcode === 0) {
			var hgtRst = result.result.hgt;
			hgtContinuousDay = hgtRst.days;
			if (hgtContinuousDay < 0) {
				hgtFlow = '流出';
				hgtContinuousDay = -hgtContinuousDay;
			}

			var sgtRst = result.result.sgt;
			// var sgtFlow = '流入';
			// var sgtContinuousDay = sgtRst.days;
			// if (sgtContinuousDay < 0) {
			// 	sgtFlow = '流出';
			// 	sgtContinuousDay = -sgtContinuousDay;
			// }

			self.beginDate = sgtRst.latesttradeday;
			var beginDate = publicMethod.dateSplit(self.beginDate);
			$('#' + self.domId + 'DatePicker').val(beginDate);
			self.originalDateStr = beginDate;
		}
		var flowGrade = '';
		hsgtModel.requestData(self.beginDate, false, async function(result) {
			// self.analyticalData(result);
			var hgtData = [],
				sgtData = [];
			if (result.length > 0) {
				result = result[0];
				$.each(result.hgt.data, function(i, val) {
					hgtData.push(parseFloat(val['value']));
				});
				$.each(result.sgt.data, function(i, val) {
					sgtData.push(parseFloat(val['value']));
				});

				self.latestVal1 = hgtData[hgtData.length - 1];
				self.latestVal2 = sgtData[sgtData.length - 1];

				if (self.latestVal1 < -20) {
					flowGrade = '放量净流出';
				} else if (self.latestVal1 < -10) {
					flowGrade = '放量净流出';
				} else if (self.latestVal1 < 0) {
					flowGrade = '温和净流出';
				} else if (self.latestVal1 < 10) {
					flowGrade = '小幅流入';
				} else if (self.latestVal1 < 30) {
					flowGrade = '温和流入';
				} else if (self.latestVal1 > 30) {
					flowGrade = '大幅流入';
				}
				$('#' + self.domId + 'ExplainData').html('沪股通资金' + flowGrade + '，连续' + hgtFlow + hgtContinuousDay + '天');
				$('#' + self.domId + 'ExplainBtn').show();
			} else {
				$('#' + self.domId + 'ExplainBtn').hide();
				self.latestVal1 = '--';
				self.latestVal2 = '--';

			}
			self.renderExplain(self.latestVal1);

			if (isUpdate) {
				self.HighchartsObj.series[0].update({
					data: hgtData
				});
				self.HighchartsObj.series[1].update({
					data: sgtData
				});
				$('.hgt-legend').text(self.latestVal1);
				$('.sgt-legend').text(self.latestVal2);
			} else {
				await self.drawChart(hgtData, sgtData, self.latestVal1, self.latestVal2);
			}

		});
	}

	HsgtzjModule.prototype.analyticalData = async function(result1, result2) {
		var hgtFlow = '流入';
		var hgtContinuousDay = 0;

		var hgtRst = result1.result1.hgt;
		hgtContinuousDay = hgtRst.days;
		if (hgtContinuousDay < 0) {
			hgtFlow = '流出';
			hgtContinuousDay = -hgtContinuousDay;
		}

		var sgtRst = result1.result1.sgt;

		self.beginDate = sgtRst.latesttradeday;
		var beginDate = publicMethod.dateSplit(self.beginDate);
		$('#' + self.domId + 'DatePicker').val(beginDate);
		self.originalDateStr = beginDate;


		var flowGrade = '';

		var hgtData = [],
			sgtData = [];
		if (result2.length > 0) {
			result2 = result2[0];
			$.each(result2.hgt.data, function(i, val) {
				hgtData.push(parseFloat(val['value']));
			});
			$.each(result2.sgt.data, function(i, val) {
				sgtData.push(parseFloat(val['value']));
			});

			self.latestVal1 = hgtData[hgtData.length - 1];
			self.latestVal2 = sgtData[sgtData.length - 1];

			if (self.latestVal1 < -20) {
				flowGrade = '放量净流出';
			} else if (self.latestVal1 < -10) {
				flowGrade = '放量净流出';
			} else if (self.latestVal1 < 0) {
				flowGrade = '温和净流出';
			} else if (self.latestVal1 < 10) {
				flowGrade = '小幅流入';
			} else if (self.latestVal1 < 30) {
				flowGrade = '温和流入';
			} else if (self.latestVal1 > 30) {
				flowGrade = '大幅流入';
			}
			$('#' + self.domId + 'ExplainData').html('沪股通资金' + flowGrade + '，连续' + hgtFlow + hgtContinuousDay + '天');
			$('#' + self.domId + 'ExplainBtn').show();
		} else {
			$('#' + self.domId + 'ExplainBtn').hide();
			self.latestVal1 = '--';
			self.latestVal2 = '--';
		}

		self.renderExplain(self.latestVal1);

		if(self.HighchartsObj) {
			self.HighchartsObj.series[0].update({
				data: hgtData
			});
			self.HighchartsObj.series[1].update({
				data: sgtData
			});
			$('.hgt-legend').text(self.latestVal1);
			$('.sgt-legend').text(self.latestVal2);
		} else {
			await self.drawChart(hgtData, sgtData, self.latestVal1, self.latestVal2);
		}
	}


	HsgtzjModule.prototype.requestDayData = function(sdate, edate) {
		var self = this;
		hsgtModel.requestData(sdate, edate, async function(result) {
			var hgtData = [],
				sgtData = [];

			var _dateArr = [],
				dateArr = [];
			$.each(result, function(i, val) {
				var latestData = val.hgt.data.pop();
				var latestVal = latestData['value'];
				hgtData.push(parseFloat(latestVal));
				dateArr.push(val.hgt.date.substr(5));

				var latestData2 = val.sgt.data.pop();
				var latestVal2 = latestData2['value'];
				sgtData.push(parseFloat(latestVal2));

			});

			self.latestVal1 = hgtData[hgtData.length - 1];
			self.latestVal2 = sgtData[sgtData.length - 1];

			// self.renderExplain(ztNewestData);
			await self.drawChart(hgtData, sgtData, self.latestVal1, self.latestVal2, dateArr);
		});
	}


	HsgtzjModule.prototype.renderExplain = function(data) {
		var self = this;
		var gradePic = '12';
		if (data <= -20) {
			gradePic = 1;
		} else if (data <= -15) {
			gradePic = 2;
		} else if (data <= -10) {
			gradePic = 3;
		} else if (data <= -5) {
			gradePic = 4;
		} else if (data <= 0) {
			gradePic = 5;
		} else if (data <= 5) {
			gradePic = 6;
		} else if (data <= 10) {
			gradePic = 7;
		} else if (data <= 15) {
			gradePic = 8;
		} else if (data <= 20) {
			gradePic = 9;
		} else {
			gradePic = 10;
		}

		$('.' + self.domId + '-explain-pic').css('background-position', -177 * gradePic + 'px 0');
	}

	HsgtzjModule.prototype.getExplainData = async function(date) {
		var hour = await clientApi.serverHour();

		if (hour > 0945) {
			this.requestZxData(this.hcType, date);
		} else {
			this.renderRisingProb(this.hcType, '');
		}
	}
	HsgtzjModule.prototype.bindEvents = async function() {
		var self = this;
		var tradeDay = await clientApi.getTradingDay();

		var minDate = '2016-01-04';

		this.datePicker(tradeDay, this.domId, function(date) {
			self.requestMinData(date);
		}, function(sdate, edate) {
			self.requestDayData(sdate, edate);
		}, minDate);

		var hoverTimer;
		$('#' + self.domId + 'ExplainBtn').hover(function() {
			var _this = this;
			hoverTimer = setTimeout(function() {
				$(_this).find('b').show();
				$(_this).parents('.module-item').find('.explain-box').show();
			}, 1000)
		}, function() {
			clearTimeout(hoverTimer);
		});

		$('#' + self.domId + 'ExplainBox').mouseleave(function() {
			$(this).parents('.module-item').find('b.icon').hide();
			$(this).hide();
		});
	}

	HsgtzjModule.prototype.drawChart = function(series1, series2, latestVal1, latestVal2, dateArr) {
		var self = this;
		var _tickPositions = [0, 140, 261];
		_tickInterval = '120',
			_xAxisMin = '0',
			_xAxisMax = '261',
			_xAxisData = publicMethod.hsgtXAxisData;

		if (self.type == 'day') {
			_tickPositions = null;
			_tickInterval = Math.ceil(dateArr.length / 10);
			_xAxisMin = null,
				_xAxisMax = null,
				_xAxisData = dateArr;
		}
		var chartOptions = {
			credits: {
				enabled: false
			},
			title: {
				text: ''
			},
			chart: {
				backgroundColor: null,
				style: {
					"fontFamily": "Arial, \"Microsoft yahei\", Verdana, Helvetica, sans-serif",
					"fontSize": "12px"
				},
				marginTop: 40,
				marginLeft: 40,
				marginBottom: 30
			},
			series: [{
				name: '当日沪股通资金',
				type: 'line',
				color: '#6EB4E5',
				lineWidth: 1,
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#6EB4E5',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 1
						}
					}
				},
				data: series1
			}, {
				name: '当日深股通资金',
				type: 'line',
				color: '#F86A4E',
				lineWidth: 1,
				marker: {
					enabled: false,
					states: {
						hover: {
							fillColor: '#F86A4E',
							radius: 2,
							lineColor: 'rgba(255, 255, 255, 1)',
							lineWidthPlus: 1
						}
					}
				},
				data: series2
			}],
			plotOptions: {
				line: {
					states: {
						hover: {
							lineWidthPlus: 0
						}
					}
				}
			},
			xAxis: {
				lineWidth: 1,
				tickLength: 4,
				lineColor: '#808080',
				tickColor: '#808080',
				tickInterval: _tickInterval,
				tickPositions: _tickPositions,
				title: {
					text: ''
				},
				categories: _xAxisData,
				gridLineWidth: 0,
				labels: {
					align: 'center',
					rotation: 0,
					style: {
						color: '#afafaf'
					}
				},
				min: _xAxisMin,
				max: _xAxisMax
			},
			yAxis: {
				allowDecimals: false,
				lineWidth: 1,
				tickColor: '#808080',
				tickPosition: 'outside',
				gridLineWidth: 0,
				tickLength: 4,
				tickWidth: 1,
				title: {
					text: ''
				},
				lineColor: '#808080',
				labels: {
					// format: '{value}%',
					style: {
						color: '#afafaf'
					},
					x: -7
				},
				plotLines: [{
					value: 0,
					width: 1,
					color: '#808080',
					dashStyle: 'Dash'
				}]
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				floating: false,
				symbolHeight: 10,
				symbolWidth: 14,
				itemStyle: {
					color: '#dedede',
					fontFamily: 'Microsoft yahei',
					fontWeight: 'normal'
				},
				itemHiddenStyle: {},
				itemHoverStyle: {
					color: '#bbb'
				},
				useHTML: true,
				labelFormatter: function() {
					if (this.name === '当日沪股通资金') {
						return '<span class="legend-item">当日沪股通资金 <i class="hgt-legend">' + latestVal1 + '</i></span>';
					} else {
						return '<span class="legend-item">当日深股通资金 <i class="sgt-legend">' + latestVal2 + '</i></span>';
					}
				}
			},
			tooltip: {
				shared: true,
				backgroundColor: '#2e3339',
				borderColor: '#505458',
				shape: '',
				crosshairs: [{
					width: 1,
					color: '#afafaf'
				}],
				valueDecimals: 2,
				valueSuffix: '亿',
				style: {
					fontFamily: 'Microsoft yahei',
					color: '#fff'
				}
			}
		};

		$('#' + self.domId + 'ChartBox').highcharts(chartOptions);
		self.HighchartsObj = $('#' + self.domId + 'ChartBox').highcharts();
	}

	HsgtzjModule.prototype.updateSeries = function (isHasOverall, date, result1, result2) {
		var self = this;
		if (isHasOverall) {
			return;
		}
		var inputDate = $('#'+ self.domId + 'DatePicker').val();
		var isToday = inputDate.replace(/-/g, '') == date;

		if (this.type == 'min' && isToday) {
			if (result1 && result2) {
				self.analyticalData(result1, result2);
				self.getExplainData(date);
			} else {
				hsgtModel.getIsTrading(date, function(result) {
					self.checkIsTrading(result, 'isUpdate');
				});
				self.getExplainData(date);
			}
		}
	}

	module.exports = HsgtzjModule;
});